<?php

namespace App\Models;

use Carbon\Carbon;
use Dcat\Admin\Traits\HasDateTimeFormatter;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class ReservationLog extends Model
{
    use HasFactory, HasDateTimeFormatter;

    const STATUS_OPTIONS = [
        0 => '预约成功',
        1 => '预约取消',
        2 => '预约过期',
    ];

    protected $casts = [
        'date' => 'date'
    ];

    protected $fillable = [
        'name',
        'date',
        'time',
        'phone',
        'remark',
        'user_id',
    ];

    public function projects(): \Illuminate\Database\Eloquent\Relations\BelongsToMany
    {
        return $this->belongsToMany(Project::class, 'reservation_has_project', 'reservation_id', 'project_id');
    }

    /**
     * 返回 状态文本
     * @return array|mixed
     */
    public function getStatusTextAttribute(): mixed
    {
        return data_get(self::STATUS_OPTIONS, $this->status);
    }

    /**
     * @param array $projects
     * @param Carbon $date
     * @param string $time
     * @param array|null $excludeReservation
     * @return bool
     */
    public static function checkTimeCanUse(array $projects, Carbon $date, string $time, array $excludeReservation = null): bool
    {
        $projectData = Project::getProjectsAndDetail($projects, $date, $excludeReservation);
        foreach ($projectData as $project) {
            $project->getTimeResult($date);

            foreach ($project->timeResult as $key => $item) {
                if (hasOverlap($key, $time)) {
                    if ($item <= 0) return false;
                }
            }
        }
        return true;
    }

    public function toArray(): array
    {
        $arr = parent::toArray(); // TODO: Change the autogenerated stub
        $arr['date'] = $this->date->toDateString();
        $arr['status_text'] = $this->status_text;
        $arr['project_name'] = $this->projects->pluck("title")->join(',');
        return $arr;
    }

}
